package com.tyjc.unique.ssq;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.tyjc.unique.AnaylaseBaseFragment;
import com.tyjc.unique.net.StringResultBean_New;
import com.tyjc.unique.util.SSQ_ZhuShu;
import com.tyjc.unique.view.RandomSetView;
import com.fyzk.activity.app.AppToast;
import com.fyzk.activity.gl.SSQGLResultActivity;
import com.fyzk.activity.lottery.shuzicai.BallInfo;
import com.fyzk.activity.lottery.shuzicai.SelectBallView;
import com.fyzk.activity.lottery.shuzicai.TouZhuHelper;
import com.fyzk.activity.myview.WeiZhi;
import com.fyzk.bean.CurrentPhaseInfo;
import com.fyzk.betcode.AppLotteryCodeListManager;
import com.fyzk.data.AppLotteryInfos;
import com.tyjc.lottery.R;
import com.fyzk.net.Commands;
import com.fyzk.utils.LotteryIDUtils;
import com.fyzk.utils.RandomUtil;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;

import http.Common.CommandUtil;


/**
 * 双色球过滤类
 *
 * @author miao
 */

@ContentView(R.layout.fg_ssqfilter)
public class SSQFilterFragment extends AnaylaseBaseFragment implements
        RandomSetView.RandomBtnClickListener, TouZhuHelper.BallClickListener, TouZhuHelper
        .BallItemClickLitener {

    protected SelectBallView redBallView;
    protected SelectBallView blueBallView;

    protected RandomSetView redRandomSet;
    protected RandomSetView blueRandomSet;

    protected List<BallInfo> redBallInfos = new ArrayList<BallInfo>();
    protected List<BallInfo> blueBallInfos = new ArrayList<BallInfo>();

    protected List<List<BallInfo>> arrs = new ArrayList<List<BallInfo>>();

    private TextView mTxt_amount;// 注码彩金
    private RadioGroup mRdg_fs;

    private final int Z6B5 = 2;
    private final int Z6B4 = 1;
    private final int Z5B5 = 4;
    private final int Z5B4 = 3;
    private int type_fs = Z6B5;//

    private String red_code = "";
    private String blue_code = "";

    @ViewInject(R.id.btn_filter)
    private Button btn_filter;

    private int minRed = 8;

    long zhushu;


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        redBallView = view.findViewById(R.id.redball);
        blueBallView = view.findViewById(R.id.blueball);
        initRandomSetView(view);
        initBallList();
        arrs.add(redBallInfos);
        arrs.add(blueBallInfos);
        redBallView.setBallInfoList(redBallInfos);
        blueBallView.setBallInfoList(blueBallInfos);
        initBallViewMax();
        mTxt_amount = view.findViewById(R.id.select_amount);
        mRdg_fs = view.findViewById(R.id.gl_rdg);
        btn_filter.setOnClickListener(this);
        mRdg_fs.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.gl_rdb_z6b5:// 中6包5
                        type_fs = Z6B5;
                        redRandomSet.setRandomNumRange(8, 17);
                        redBallView.setSelect_max(17);
                        minRed = 8;
                        redRandomSet.setLineTitle("红球（8~17）");
                        break;
                    case R.id.gl_rdb_z6b4:// 中6保4
                        type_fs = Z6B4;
                        redRandomSet.setRandomNumRange(8, 17);
                        redBallView.setSelect_max(17);
                        minRed = 8;
                        redRandomSet.setLineTitle("红球（8~17）");
                        break;
                    case R.id.gl_rdb_z5b5:// 中5保5
                        type_fs = Z5B5;
                        redRandomSet.setRandomNumRange(8, 17);
                        redBallView.setSelect_max(17);
                        minRed = 8;
                        redRandomSet.setLineTitle("红球（8~17）");
                        break;
                    case R.id.gl_rdb_z5b4:// 中5保4
                        type_fs = Z5B4;
                        redRandomSet.setRandomNumRange(8, 17);
                        redBallView.setSelect_max(17);
                        minRed = 8;
                        redRandomSet.setLineTitle("红球（8~17）");
                        break;
                    case R.id.gl_rdb_nil:
                        type_fs = 0;
                        break;
                }
            }
        });
        TouZhuHelper.getInstance().setBallItemClickLitener(this);
        TouZhuHelper.getInstance().setBallClickListener(this);
        findCurrentPhase();
    }

    private void findCurrentPhase() {
        try {
            JSONObject params = new JSONObject();
            params.put("lotteryType", LotteryIDUtils.SSQ_LOTTERY_ID_INT);
            httpPostJson(CommandUtil.FINDCURRENTPHASE, Commands.FINDCURRENTPHASE, params, false);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onSuccess(int requestCode, StringResultBean_New resultBean, String result) {
        super.onSuccess(requestCode, resultBean, result);
        switch (requestCode){
            case CommandUtil.FINDCURRENTPHASE:
                CurrentPhaseInfo info = JSON.parseObject(resultBean.getData(),
                        CurrentPhaseInfo.class);
                AppLotteryInfos.setCurrentPrizeInfo(info);
                break;
        }
    }
    /**
     * 是否可以过滤
     *
     * @return
     */
    public boolean glAble() {
        return zhushu > 0 && getRedSelectNum() >= minRed;
    }

    private void initCode() {
        StringBuffer red = new StringBuffer();
        StringBuffer blue = new StringBuffer();
        for (int i = 0; i < arrs.get(0).size(); i++) {
            BallInfo info = arrs.get(0).get(i);
            if (info.isSelected()) {
                red.append(info.getNum()).append(",");
            }
        }
        if (red.length() > 1) {
            red.deleteCharAt(red.length() - 1);
            red_code = red.toString();
        }
        for (int i = 0; i < arrs.get(1).size(); i++) {
            BallInfo info = arrs.get(1).get(i);
            if (info.isSelected()) {
                blue.append(info.getNum()).append(",");
            }
        }
        if (blue.length() > 1) {
            blue.deleteCharAt(blue.length() - 1);
            blue_code = blue.toString();
        }
    }

    public int getRedSelectNum() {
        int selectNum = 0;
        for (BallInfo info : redBallInfos) {
            if (info.isSelected()) {
                selectNum++;
            }
        }
        return selectNum;
    }


    @Override
    public void onStart() {
        super.onStart();

    }



    private void requestGL() {

        Intent intent = new Intent(getContext(), SSQGLResultActivity.class);
        intent.putExtra("type_fs",type_fs);
        intent.putExtra("red_code",red_code);
        intent.putExtra("blue_code",blue_code);
        getContext().startActivity(intent);


    }


    public void initRandomSetView(View view) {
        blueRandomSet = view.findViewById(R.id.randomSet_blue);
        redRandomSet = view.findViewById(R.id.randomSet_red);
        redRandomSet.setRandomNumRange(8, 17);
        blueRandomSet.setRandomNumRange(1, 12);
        redRandomSet.setOnRandomBtnClickListener(this);
        blueRandomSet.setOnRandomBtnClickListener(this);
        redRandomSet.setTag_line("红球",R.drawable.ball_red);
        blueRandomSet.setTag_line("蓝球",R.drawable.ball_blue);
    }

    public void initBallViewMax() {
        redBallView.setSelect_max(17);
    }

    /**
     * 初始化 小球list
     *
     * @param balls
     * @param count 每列显示小球数
     * @param start
     */
    public void initBallList(List<BallInfo> balls, int count, int start,
                             boolean hasZero) {
        balls.clear();
        for (int j = start; j < count + start; j++) {
            BallInfo qiu;
            if (hasZero) {
                if (j < 10) {
                    qiu = new BallInfo("0" + j);
                } else {
                    qiu = new BallInfo("" + j);
                }
            } else {
                qiu = new BallInfo(String.valueOf(j));
            }
            balls.add(qiu);
        }
    }

    public void initBallList() {
        initBallList(redBallInfos, 33, 1, true);
        initBallList(blueBallInfos, 16, 1, true);
    }

    @Override
    public void onRandomBtnClick(RandomSetView v, int randomCount) {
        switch (v.getId()) {
            case R.id.randomSet_red:
                int redArr[] = RandomUtil.randomNoRepeat(randomCount, 0, 33);
                initBallList(redBallInfos, 33, 1, true);
                for (int i = 0; i < redArr.length; i++) {
                    redBallInfos.get(redArr[i]).setSelected(true);
                }
                redBallView.invalidate();
                break;
            case R.id.randomSet_blue:
                int blueArr[] = RandomUtil.randomNoRepeat(randomCount, 0, 16);
                initBallList(blueBallInfos, 16, 1, true);
                for (int i = 0; i < blueArr.length; i++) {
                    blueBallInfos.get(blueArr[i]).setSelected(true);
                }
                blueBallView.invalidate();
                break;

            default:
                break;
        }
        ballClick(null);
    }

    @Override
    public void showData() {
        super.showData();
    }

    @Override
    public void onClick(View arg0) {
        super.onClick(arg0);
        if (glAble()) {
            initCode();
            requestGL();
        } else {
            AppToast.getToast().show("红球个数至少为8个，篮球至少选择1个！");
        }

    }

    @Override
    public void ballClick() {
        ballClick(null);
    }

    @Override
    public void ballClick(WeiZhi wz) {
        zhushu = new SSQ_ZhuShu().betZhuShu(arrs);
        mTxt_amount.setText("总计，" + zhushu + "注 " + zhushu * 2 + "米");
    }

    @Override
    public void onDestroy() {
        AppLotteryCodeListManager.betType = AppLotteryCodeListManager.FIRSTENTER;
        AppLotteryCodeListManager.getInstance().getList().clear();
        AppLotteryCodeListManager.chooseId = 0;
        super.onDestroy();
        TouZhuHelper.getInstance().detachBallClickListener(this);
        TouZhuHelper.getInstance().detachBallItemClickListener(this);
    }
}
